//
//  MapLayer.m
//  cocos2dFirstTest
//
//  Created by Daniel Alexander on 6/20/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MapLayer.h"

@implementation MapLayer

-(id)init{
    if( (self=[super init])) {
        
        screenWidth = [[CCDirector sharedDirector] winSizeInPixels].width;
        screenHeight = [[CCDirector sharedDirector] winSizeInPixels].height;
        
        tileWall = [CCSprite spriteWithFile:@"wall.png"];
        tileFloor = [CCSprite spriteWithFile:@"floor.png"];
        
        Legend = [NSMutableDictionary dictionary];
        [Legend setObject:@"wall.png" forKey:@"#"];
        [Legend setObject:@"floor.png" forKey:@" "];
        
        theParty = [NSDictionary dictionary];
        
        _myPlayer = [[NSUserDefaults standardUserDefaults] objectForKey:@"playername"];
        NSString *class;
        class = [[NSUserDefaults standardUserDefaults] objectForKey:@"playerclass"];
        if ([class isEqualToString:@"warrior"])
        {
            playerSprite = [CCSprite spriteWithFile:@"warrior.png"];
        }else
        {
            playerSprite = [CCSprite spriteWithFile:@"mage.png"];
        }
        [self addChild:playerSprite z:9999];
        
        debugLabel = [CCLabelTTF labelWithString:@"" fontName:@"font.ttf" fontSize:14];
        debugLabel.position = ccp(300,240);
        debugLabel.color = ccc3(255, 255, 255);
        [self addChild:debugLabel];
        
        partyLegend = [[NSMutableDictionary dictionary] retain];
        
        [self scheduleUpdate];
	}
    return self;
}

-(void) SetMap:(NSMutableDictionary*)newMap{
    //fill with dictionary map
    NSLog(@"filling map data from dictionary.");
    for (int y = 0; y < 50; ++y)
    {
        for (int x = 0; x < 90; ++x)
        {
            map[y][x] = '\0'; //null
        }
    }
    
    NSInteger startx = -1;
    NSInteger starty = -1;
    
    //PARSE THE DICTIONARY FOR THE MAP'S DATA
    for (NSString* key in newMap)
    {
       
        id value = [newMap objectForKey:key];
        if ([key isEqualToString:@"spawn"])
        {
            //PLAYER SPAWN POSITION
            NSLog(@"getting starting location...");
            startx = [[[value objectForKey:@"main"] objectForKey:@"x"] integerValue];
            starty = [[[value objectForKey:@"main"] objectForKey:@"y"]   integerValue];
        }else if ([key isEqualToString:@"height"])
        {
            //HEIGHT OF THE MAP
            NSLog(@"got height");
        }else if ([key isEqualToString:@"width"])
        {
            //WIDTH OF THE MAP
            NSLog(@"got width");
        }
        else if ([key isEqualToString:@"monsters"])
        {
            //this is a catch. Ian is currently fixing this.
        }
        else{
            //EACH CELL OF THE MAP
            NSInteger y = [key integerValue];
            NSInteger x;
            for (NSString *column in value)
            {
                id colVal = [value objectForKey:column];
                x = [column integerValue];
                //NSLog(@"setting map data...");
                id asciiTile = [colVal objectForKey:@"ascii"];
                //NSLog(@"value is: %@", asciiTile);
                //map[x][y] = [asciiTile charValue];
                //char test = [asciiTile characterAtIndex:0];
                //NSString *temp = [asciiTile stringValue];
                map[y][x] = [asciiTile characterAtIndex:0];
            }
        }
    }
    
    //FILL IN THE FLOOR
    NSLog(@"filling in floor");
    [self fill_floor_rec:startx yvalue:starty target:'\0' replacement:' '];
    
    NSLog(@"creating sprite tiles");
    //NOW ADD SPRITES
    int count = 0;
    //NSString *mess = @"";
    for (int y = 0; y < 50; ++y)
    {
        for (int x = 0; x < 50; ++x)
        {
            if (map[y][x] == '#')
            {
                tiles[count] = [CCSprite spriteWithFile:@"wall.png"];
            }else if (map[y][x] == ' ')
            {
               tiles[count] = [CCSprite spriteWithFile:@"floor.png"];
            }else{
                //tiles[count] = [CCSprite spriteWithFile:@"mage.png"];
            }
            
            if (map[y][x] != '\0' && tiles[count] != NULL)
            {
                tiles[count].position = ccp(x*32+16,screenHeight-(y*32)+16);
                [self addChild:tiles[count] z:0];
                ++count;
            }
            //mess = [mess stringByAppendingFormat:@"%c",map[y][x]];
        }
        //NSLog(@"%@",mess);
        //mess = @"";
    }
    totalTiles = count;
    
    _maploaded = YES;
}

-(void) fill_floor_rec:(NSInteger) x  yvalue:(NSInteger) y target:(char)target replacement:(char)replacement{
    
    //make sure it is inside bounds
    if (x < 0 || x >= 90 || y < 0 || y >= 50)
        return; //if not in the bounds
    
    //check for target
    if (map[x][y] != target)
        return; //because it doesn't have the target tile
    
    //replace
    map[x][y] = replacement;
    
    //go each direction
    [self fill_floor_rec:x+1 yvalue:y target:target replacement:replacement];
    [self fill_floor_rec:x-1 yvalue:y target:target replacement:replacement];
    [self fill_floor_rec:x yvalue:y-1 target:target replacement:replacement];
    [self fill_floor_rec:x yvalue:y+1 target:target replacement:replacement];
    
    /*
     x = Integer(node[0])
     y = Integer(node[1])
     #check for target
     if @tiles[node[0].to_s()][node[1].to_s()] != nil then return end
     
     @tiles[node[0].to_s()][node[1].to_s()] = Hash.new
     @tiles[node[0].to_s()][node[1].to_s()]["ascii"] = replacement
     
     #go one tile in each direction
     fill_floor_rec([x+1,y],target,replacement) #east
     fill_floor_rec([x-1,y],target,replacement) #west
     fill_floor_rec([x,y-1],target,replacement) #north
     fill_floor_rec([x,y+1],target,replacement) #south
     */
}

-(void)ChangeView:(NSInteger)x yvalue:(NSInteger)y{
    //center on the x and y
    self.position = ccp(x - screenWidth / 2, y + screenHeight / 2);
}

-(void)UpdateParty:(NSDictionary *)party{
    theParty = party;
    partyUpdated = YES;
}

-(void)SetMyPlayer:(NSString*)playerName{
    _myPlayer = playerName;
}

-(void)update:(ccTime)deltaTime{
    //update the view based on player position
    if (partyUpdated == YES)
    {
        NSInteger pX = -1;
        NSInteger pY = -1;
        int currentPerson = 0;
        for (NSDictionary* player in theParty)
        {
            if ([[player objectForKey:@"name"] isEqualToString:_myPlayer])
            {
                //this is our player's character
                pX = [[player objectForKey:@"x"] integerValue];
                pY = [[player objectForKey:@"y"] integerValue];
                
                //playerSprite.position = ccp(0,320);
                
                break;
            }else{
                //other players
                if ([partyLegend objectForKey:[player objectForKey:@"name"]] == nil)
                {
                    NSString *name = [player objectForKey:@"name"];
                    //we haven't gotten this player yet, so create info for him.
                    if ([[player objectForKey:@"class"] isEqualToString:@"warrior"])
                    {
                        [partyLegend setObject:[CCSprite spriteWithFile:@"warrior.png"] forKey:name];
                    }else if ([[player objectForKey:@"class"] isEqualToString:@"mage"])
                    {
                        [partyLegend setObject:[CCSprite spriteWithFile:@"mage.png"] forKey:name];
                    }

                    NSInteger personX = [[player objectForKey:@"x"] integerValue];
                    NSInteger personY = [[player objectForKey:@"y"] integerValue];
                
                    [[partyLegend objectForKey:name] setPositionInPixels:CGPointMake(personX*32+16, screenHeight-personY * 32 + 16)];                    
                    [self addChild:[partyLegend objectForKey:name]];
                    ++partySize;
                }
                else{
                    NSInteger personX = [[player objectForKey:@"x"] integerValue];
                    NSInteger personY = [[player objectForKey:@"y"] integerValue];
                    [[partyLegend objectForKey:[player objectForKey:@"name"]] setPositionInPixels:CGPointMake(personX*32+16, screenHeight-personY * 32 + 16)];  
                }
            }
        }
        if (pX != -1 && pY != -1)
        {
            pX = (pX * 32) + 16; //32 = tile size
            pY = screenHeight-pY * 32 + 16;
            playerSprite.position = ccp(pX,pY);
            NSLog(@"player pos in pixels:%i,%i",pX,pY);
            self.position = ccp(-(pX - screenWidth/2),-pY + screenHeight / 2);
            //self.position = ccp(-80,0);
            NSLog(@"screen size: %f,%f",[self boundingBox].size.width,[self boundingBox].size.height);
            NSLog(@"screen pos in pixels: %f,%f",self.position.x,self.position.y);
            //debugLabel.position = ccp(pX,pY);
        }
        
        if (partyLegend != nil && theParty != nil)
        {
        for (NSString *key in partyLegend)
        {
            BOOL found = NO;
            for (NSDictionary *player in theParty)
            {
                if ([[player objectForKey:@"name"] isEqualToString:key])
                {
                //the player is no longer connected, so remove them from the screen
                    found = YES;
                }
            }
            
            if (found == NO)
            {
                [self removeChild:[partyLegend objectForKey:key] cleanup:YES];
                [partyLegend removeObjectForKey:key];
            }
        }
        }
        
        partyUpdated = NO;
    }
}

-(BOOL) IsMapLoaded{
    return _maploaded;
}

- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
    for (int i = 0; i < (90*50); ++i)
        [tiles[i] dealloc];
    
	// don't forget to call "super dealloc"
	[super dealloc];
}

@end
